package com.boot.controller;

import com.boot.shiro.LoginToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return "redirect:/index";
        }
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Map doLogin(Map map,
                       LoginToken token) {
        try {
            SecurityUtils.getSubject().login(token);
            map.put("success", true);
        } catch (UnknownAccountException e) {
            map.put("msg", "账号不存在!");
        } catch (IncorrectCredentialsException e) {
            map.put("msg", "用户名/密码错误!");
        } catch (ExcessiveAttemptsException e) {
            map.put("msg", "账户错误次数过多,暂时禁止登录!");
        } catch (Exception e) {
            map.put("msg", "未知错误!");
        }

        return map;
    }
}
